﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;

namespace AsscerMVCN2512.Controllers
{
    public class AssetInfoController : Controller
    {
        AssetDBEntities1 db = new AssetDBEntities1();
        // GET: AssetInfo
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetData(int page, int limit, string strAssetName, int? strAssetTypeID)
        {
            int offset = limit * (page - 1);

            // 修正：添加 ORDER BY 子句，按 ID 倒序排列
            string sql = "select a.* ,b.AssetTypeName from AssetInfo a left join AssetTypeInfo b on a.AssetTypeId=b.AssetTypeId where 1=1";

            if (!string.IsNullOrEmpty(strAssetName))
            {
                sql += " and a.AssetName like '%" + strAssetName + "%'";
            }
            if (strAssetTypeID != null && strAssetTypeID != 0)
            {
                sql += " and a.AssetTypeId=" + strAssetTypeID;
            }

            // 添加排序，新的数据在前
            sql += " ORDER BY a.AssetId DESC";

            List<AssetInfoViewModel> list = db.Database.SqlQuery<AssetInfoViewModel>(sql).ToList();
            var data = list.Skip(offset).Take(limit); // 移除原来的排序

            db.Configuration.LazyLoadingEnabled = false;
            var json = new
            {
                code = 0,
                msg = "",
                count = list.Count,
                data = data
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Save(AssetInfo model)
        {
            try
            {
                if (model == null)
                {
                    return Json(new { code = 1, msg = "数据不能为空" });
                }

                // 数据验证
                if (string.IsNullOrEmpty(model.AssetName))
                {
                    return Json(new { code = 1, msg = "资产名称不能为空" });
                }

                // 修正：使用正确的空值判断
                if ( model.AssetTypeID == 0)
                {
                    return Json(new { code = 1, msg = "请选择资产类别" });
                }

                // 判断是新增还是编辑
                if (model.AssetID == 0)
                {
                    // 新增
                    db.AssetInfo.Add(model);
                    db.SaveChanges();
                    return Json(new { code = 0, msg = "添加成功" });
                }
                else
                {
                    // 编辑 - 修正：确保能找到现有记录
                    var existing = db.AssetInfo.Find(model.AssetID);
                    if (existing == null)
                    {
                        return Json(new { code = 1, msg = "资产不存在" });
                    }

                    // 更新字段 - 确保所有字段都更新
                    existing.AssetName = model.AssetName;
                    existing.AssetTypeID = model.AssetTypeID;
                    existing.AssetModel = model.AssetModel ?? "";
                    existing.AssetCompany = model.AssetCompany ?? "";
                    existing.AssetReMark = model.AssetReMark ?? "";

                    db.Entry(existing).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();

                    return Json(new { code = 0, msg = "更新成功" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "操作失败：" + ex.Message });
            }
        }

        // 添加删除方法
        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                var asset = db.AssetInfo.Find(id);
                if (asset == null)
                {
                    return Json(new { code = 1, msg = "资产不存在" });
                }

                // 检查是否有关联数据，防止外键约束冲突
                bool hasRelatedData = db.AssetDetailInfo.Any(x => x.AssetID == id);
                if (hasRelatedData)
                {
                    return Json(new { code = 1, msg = "该资产存在关联的资产明细，无法删除" });
                }

                db.AssetInfo.Remove(asset);
                db.SaveChanges();
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException dbEx)
            {
                // 处理外键约束异常
                return Json(new { code = 1, msg = "删除失败：该资产存在关联数据，无法删除" });
            }
            catch (Exception ex)
            {
                // 记录详细错误日志
                System.Diagnostics.Debug.WriteLine($"删除资产时出错: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");

                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }

        public string Exist(string name,int id=0)
        {
            AssetInfo info = new AssetInfo();
            if (id == 0)
            {
                //添加操作
                 info = db.AssetInfo.Where(x => x.AssetName == name).FirstOrDefault();
                
            }
            else
            {
                //编辑操作
                info = db.AssetInfo.FirstOrDefault(x =>x.AssetID != id&&x.AssetName==name);
            }
            if (info != null)
            {
                return "true";
            }
            else
            {
                return "false";
            }
        }
    }
}